package go_service

import (
	"context"
	"fmt"
	"os"
	"os/exec"
	"path/filepath"
	"strings"
	"text/template"
)

// ServiceConfig 用于Systemd服务文件模板的数据结构
type ServiceConfig struct {
	Name        string
	Description string
	ExecPath    string
	Args        string
	WorkingDir  string
	User        string
	Group       string
	StartType   string
	Restart     string
	WantedBy    string
	After       string
	Requires    string
}

// getServiceFilePath 获取服务文件路径
func (s *Service) getServiceFilePath() string {
	return filepath.Join("/etc/systemd/system", s.Name+".service")
}

// formatArgs 格式化命令行参数
func (s *Service) formatArgs() string {
	if len(s.Args) == 0 {
		return ""
	}
	return " " + strings.Join(s.Args, " ")
}

// formatList 格式化字符串列表
func (s *Service) formatList(items []string) string {
	if len(items) == 0 {
		return ""
	}
	return strings.Join(items, " ")
}

// generateSystemdServiceFile 生成Systemd服务文件
func (s *Service) generateSystemdServiceFile() error {
	// 确保目录存在
	serviceDir := "/etc/systemd/system"
	if err := os.MkdirAll(serviceDir, 0755); err != nil {
		return fmt.Errorf("failed to create systemd directory: %w", err)
	}

	// 准备模板数据
	config := ServiceConfig{
		Name:        s.Name,
		Description: s.Description,
		ExecPath:    s.ExecPath,
		Args:        s.formatArgs(),
		WorkingDir:  s.WorkingDir,
		User:        s.User,
		Group:       s.Group,
		StartType:   s.StartType,
		Restart:     s.RestartPolicy,
		WantedBy:    s.WantedBy,
		After:       s.formatList(s.After),
		Requires:    s.formatList(s.Requires),
	}

	// 创建服务文件
	serviceFile := s.getServiceFilePath()
	file, err := os.Create(serviceFile)
	if err != nil {
		return fmt.Errorf("failed to create service file: %w", err)
	}
	defer file.Close()

	// 生成服务文件内容
	tmpl := template.Must(template.New("service").Parse(systemdServiceTemplate))
	if err := tmpl.Execute(file, config); err != nil {
		return fmt.Errorf("failed to write service file: %w", err)
	}

	return nil
}

// reloadSystemd 重新加载Systemd配置
func (s *Service) reloadSystemd(ctx context.Context) error {
	cmd := exec.CommandContext(ctx, "systemctl", "daemon-reload")
	output, err := cmd.CombinedOutput()
	if err != nil {
		return fmt.Errorf("failed to reload systemd: %s", string(output))
	}
	return nil
}

// EnableService 启用服务开机启动
func (s *Service) EnableService(ctx context.Context) error {
	cmd := exec.CommandContext(ctx, "systemctl", "enable", s.Name)
	output, err := cmd.CombinedOutput()
	if err != nil {
		return fmt.Errorf("failed to enable service: %s", string(output))
	}
	return nil
}

// DisableService 禁用服务开机启动
func (s *Service) DisableService(ctx context.Context) error {
	cmd := exec.CommandContext(ctx, "systemctl", "disable", s.Name)
	output, err := cmd.CombinedOutput()
	if err != nil {
		return fmt.Errorf("failed to disable service: %s", string(output))
	}
	return nil
}

// IsServiceExist 检查服务是否存在
func (s *Service) IsServiceExist() bool {
	serviceFile := s.getServiceFilePath()
	_, err := os.Stat(serviceFile)
	return err == nil
}

// systemdServiceTemplate Systemd服务文件模板
const systemdServiceTemplate = `[Unit]
Description={{.Description}}
After={{.After}}
Requires={{.Requires}}

[Service]
Type={{.StartType}}
ExecStart={{.ExecPath}}{{.Args}}
WorkingDirectory={{.WorkingDir}}
{{- if .User}}
User={{.User}}
{{- end}}
{{- if .Group}}
Group={{.Group}}
{{- end}}
Restart={{.Restart}}
RestartSec=5

[Install]
WantedBy={{.WantedBy}}
`
